/**
 * @Description 基础框架服务调用实例-单表编辑服务
 * @Author  guoyanfei
 * @date 2018/01/11
 */
var serviceUrl = '/gdp'
var postPath = '/gdp'
var singleEditServices = function () {
    //新增
    var add = function () {
        $("#btn_add").click(function () {
            var data = $("#data").val();
            $.ajax({
                url: postPath + "/business/singleEditServer/singleAdd",
                type: "GET",
                data: {serviceID: serviceId, conQuery: data},
                success: function (data) {
                    $("#info").append(JSON.stringify(data) + "<br/>");
                }
            });
        });
    };
    //修改
    var update = function () {
        $("#btn_update").click(function () {
            var data = $("#data").val();
            $.ajax({
                url: postPath + "/business/singleEditServer/singleUpdate",
                type: "GET",
                data: {serviceID: serviceId, conQuery: data},
                success: function (data) {
                    $("#info").append(JSON.stringify(data) + "<br/>");
                }
            });
        });
    };
    //删除
    var del = function () {
        $("#btn_del").click(function () {
            var data = $("#data").val();
            $.ajax({
                url: postPath + "/business/singleEditServer/singleDel",
                type: "GET",
                data: {serviceID: serviceId, primaryKeys: data},
                success: function (data) {
                    $("#info").append(JSON.stringify(data) + "<br/>");
                }
            });
        });
    };
    //清空执行结果数据
    var clearResult = function () {
        $("#btn_clean").click(function () {
            $("#info").html("");
        });
    };
    //查询校验列
    var selectCoulmn = function () {
        $("#tableList").bootstrapTable({
            url: postPath + '/business/singleEditServer/selectValidateCoulmn',
            undefinedText: '-',
            method: 'GET',
            striped: true, // 是否显示行间隔色  
            cache: false, // 是否使用缓存 
            queryParams: {serviceID: serviceId},
            uniqueId: "guid", // 每一行的唯一标识 
            columns: [{
                field: 'state',
                checkbox: true,
                align: 'center',
                valign: 'middle'
            }, {
                title: '字段名称',
                field: 'dfname',
                align: 'center',
                valign: 'middle'
            }, {
                title: '字段中文名称',
                field: 'dfnameCn',
                align: 'center',
                valign: 'middle',
                editable: true
            }, {
                title: '字段类型',
                field: 'fieldType',
                align: 'center',
                valign: 'middle'
            }, {
                title: '校验名称',
                field: 'validatename',
                align: 'center',
                valign: 'middle'
            }, {
                title: '校验值',
                field: 'validatevalue',
                align: 'center',
                valign: 'middle'
            }]
        });

        //拼接新增、修改json格式
        $.ajax({
            url: postPath + '/business/singleEditServer/selectValidateCoulmn',
            type: "get",
            data: {serviceID: serviceId},
            success: function (data) {
                if (data.data != null) {
                    var strtxt = "";
                    $.each(data.data, function (i, e) {
                        if (strtxt == "") {
                            strtxt = '"' + e.dfname + '":""';
                        } else {
                            strtxt += ',"' + e.dfname + '":""';
                        }
                    });
                    $("#paramValue").html("{" + strtxt + "}");
                }
            }
        });
    };

    //下载模板
    var downTemplate = function () {
        $("#btn_downTemplate").click(function () {
            window.location.href = postPath + '/business/singleEditServer/downloadDataTemplate?serviceID=' + serviceId;
        });
    };

    //导出数据
    var exportData = function () {
        $("#btn_exportData").click(function () {
            window.location.href = postPath + '/business/singleEditServer/exportData?serviceID=' + serviceId;
        });
    };

    //初始化bootstrap-fileinput,导入数据
    var FileInput = function () {
        var oFile = new Object();

        //初始化fileinput控件（第一次初始化）
        oFile.Init = function (ctrlName, uploadUrl) {
            var control = $('#' + ctrlName);

            //初始化上传控件的样式
            control.fileinput({
                language: 'zh', //设置语言
                uploadUrl: uploadUrl, //上传的地址
                allowedFileExtensions: ['xls', 'xlsx'],//接收的文件后缀
                showUpload: true, //是否显示上传按钮
                showCaption: false,//是否显示标题
                browseClass: "btn btn-primary", //按钮样式
                maxFileCount: 6, //表示允许同时上传的最大文件个数
                enctype: 'multipart/form-data',
                validateInitialCount: true,
                previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
                msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！",
                uploadExtraData: function (previewId, index) {
                    var obj = {};
                    obj.serviceID = serviceId;
                    return obj;
                }
            });

            //导入文件上传完成之后的事件
            $("#txt_file").on("fileuploaded", function (event, data, previewId, index) {
                $("#info").append(JSON.stringify(data.response) + "<br/>");
            });

        }
        return oFile;
    };

    var eventExecuteBusinessService = function (){

        // here is add
        // here is update
        // here is delete
        $("#btn_executeAddBusinessService").click(function () {
            // here is logic to expression all content
            // first section handle param
            // get general parameter
            var input_serviceId = $("#input_serviceId").val();
            var input_pageNO = $("#input_pageNO").val();
            var input_pageSize = $("#input_pageSize").val();
            console.log("luowen general input parameter", input_serviceId, input_pageNO, input_pageSize)

            var url = preUrl + singleAddPath
            $.ajax({
                url: url,
                type: 'GET',
                data: getUrlInputParameter(),
                success: function(data){
                    console.log("luowen success execute response request", data)
                    generateCompleteUrl(url);
                    format_JS_code(url);
                    displayJsCodeResponse(data);

                },
                error: function(data){
                    console.log("luowen fail execute response request", data)
                }
            });
        });


    };

    var handleDynamicConditionParameter = function(){

        console.log("luowen execute handleDynamicConditionParameter ")
        // here is get all condition item
        var url = postPath + '/system/queryfield/getQueryFieldList';

        // here assgin value to serviceId
        $("#input_serviceId").val(serviceId);

        console.log("luowen serviceID", serviceId)
        $.ajax({
            url: url,
            type: 'GET',
            data: {serviceId: serviceId, serviceType: 1, grade: ''},
            success: function(data){
                if(data == null)
                    return;

                var appendHtml = "";
                data.forEach(function(e, i){
                    // create html object
                    console.log("luowen element", e);
                    var trObject = "<tr>";
                    trObject += "<td>" + e.fieldname + "</td>";
                    trObject += "<td>" + e.paramformat+ "</td>";
                    trObject += "<td>" + e.fieldnameCn + "</td>";
                    trObject += "<td>" + "<input type='text' style='width:100%' id=input_"+e.fieldname + " value = ''/> " + "</td>";
                    trObject += "</tr>"
                    // append
                    appendHtml += trObject;
                    input_paramDict.set(e.fieldname, "input_" + e.fieldname);
                });

                console.log("luowen appendHtml object", appendHtml)
                console.log("luowen input_paramDict", input_paramDict)
                $("#inputParameterList").append(appendHtml);
                // here is save input_param_
            },
            error: function(data){
                console.log("luowen fail dynamic condition parameter",data)
            }

        });


    };

    var getFieldConditionTable = function(){
        var url = postPath + '/system/queryfield/getQueryFieldList';

        // console.log("luowen execute getFieldConditionTable, url", url, 'serviceId', serviceId)
        // $("#tb_fieldCondition").bootstrapTable({
        //     url: url,
        //     method: 'get',
        //     undefinedText: '-',
        //     queryParams: {serviceId: serviceId, paramType: 1, serviceType: 1, grade: ''},
        //     uniqueId: "guid", // 每一行的唯一标识
        //     columns: fieldConditionColumnList
        // });

        console.log("luowen execute getFieldConditionTable complete")



    };

    return {
        init: function () {
            add();
            update();
            del();
            clearResult();
            selectCoulmn();
            downTemplate();
            exportData();

            eventExecuteBusinessService();
            // here is get all dynamic condition and set condition html
            handleDynamicConditionParameter();
            getFieldConditionTable();



            var oFileInput = new FileInput();
            oFileInput.Init("txt_file", postPath + "/business/singleEditServer/importData");
        }
    }
}();


var preUrl = "http://localhost:9000";
var input_paramDict = new Map();
input_paramDict.set('serviceID', 'input_serviceId')
input_paramDict.set('pageNO','input_pageNO')
input_paramDict.set('pageSize', 'input_pageSize');

var singleAddPath = "/business/singleEditServer/singleAdd"
var singleUpdatePath = "/business/singleEditServer/singleUpdate"
var singleDeletePath = "/business/singleEditServer/singleDel"


//服务初始化
$(function () {
    $("#sp_seviceUrl").append("服务地址：" + postPath + "/business/singleEditServer/singleAdd");
    $("#sp_seviceUrl").append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;服务ID：" + serviceId);
    $("#show_serviceUrl").append(postPath);
    $("#show_serviceId").append(serviceId);
    singleEditServices.init();

    // 批量添加
    $("#batchaAddData .p_url, #batch_url").text(postPath + "/business/singleEditServer/batchAddData/" + serviceId);

})



function getUrlInputParameter(){
    // here is build those object
    var inputParameter = {};
    input_paramDict.forEach((value, key) => {
        var inputValue = $("#" + value).val();
        if(inputValue == null || inputValue == undefined){
            inputValue = '';
        }
        var id = "#"+value;
        console.log("luowen map value", value, key, $(id).val(), id, inputValue)

        inputParameter[key] = inputValue
    });

    console.log("luowen total url parameter", inputParameter);
    return inputParameter;
}

function generateCompleteUrl(operatePath){
    var completeUrl = operatePath + "?"
    var formatParameter = getUrlInputParameter();
    console.log("luowen formatParameter", formatParameter)

    Object.keys(formatParameter).forEach( key => {
        completeUrl += "&" + key + "=" + formatParameter[key];
    })

//    var encodeUrl = encode_utf8(completeUrl);
    var encodeUrl = completeUrl;

    console.log("luowen encodeUrl", encodeUrl);
    $("#completeUrl").html(encodeUrl);
}

function encode_utf8(s) {
  return encodeURIComponent(s);
}

function format_JS_code(operatePath){
    var url =  operatePath
    var dataString = JSON.stringify(getUrlInputParameter());
    console.log("luowen dataString", dataString);

    var jsCode = "";
    jsCode += "\r\n$.ajax({";
    jsCode += "\r\n      url: " + url + ", ";
    jsCode += "\r\n      type: 'GET', ";
    jsCode += "\r\n      data: " + dataString + ", ";
    jsCode += "\r\n      success: function(responseData){" ;
    jsCode += "\r\n      }";
    jsCode += "\r\n})";

    console.log("luowen jsCode", jsCode)
    $("#generateJsCode").html(jsCode)
}

function displayJsCodeResponse(responseData){
    if(responseData == null)
        return;
    var responseContent = JSON.stringify(responseData, null, 2)
    console.log("luowen responseContent", responseContent)
    $("#displayJsCodeResponse").text(responseContent);
}
